sfrom sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, mapper, relation, sessionmaker
# Database module

from wrapper import Wrapper


Base = declarative_base()

class Wrapper(object):
	_ignore_read = []
	_ignore_write = []

	def __init__(self, obj):
		self.__dict__['_obj'] = obj

	def __getattr__(self, key):
		if key in self.__dict__:
			return self.__dict[key]
		elif key not in self._ignore_read:
			return getattr(self._obj, key)
		else:
			raise AttributeError, key

	def __setattr__(self, key, value):
		if key in self.__dict__:
			object.__setattr__(self, key, value)
		elif key not in self._ignore_write:
			setattr(self._obj, key, value)
		else:
			raise AttributeError, key

class _User(Base):
	__tablename__ = "users"
	id = Column(Integer, primary_key=True)
	name = Column(String(40))
	age = Column(Integer)
	password = Column(String(40))

	def __init__(self, name, age, password=''):
		self.name = name
		self.age = age
		self.password = password
		session.add(self)
		session.commit()

	def __repr__(self):
		return "<User('%s','%s', '%s')>" % (self.name, self.age, self.password)


class UserInterface(Wrapper):
    _ignore_read = ['password']
    _ignore_write = ['name']

    @staticmethod
    def from_user(cls, row):
         return cls(row.name, row.age, row.password)

    def __init__(self, name, age, password):
        super(Wrapper, self).__init__(_User(name, age, password))


class Database:
    def __init__(dbtype, username, password, hostname, port, dbname):
        """Initiate the database"""
        db = create_engine("%s://%s:%s@%s:%s/%s" %(dbtype, username, password, hostname, port, dbname))
        db.echo = False
        users = User.__table__
        metadata = Base.metadata
        metadata.drop_all(db, checkfirst=True)
        metadata.create_all(db)
        Session = sessionmaker(bind=db)
        self._session = Session()

    #control can get all the profiles dont know why it would need it
    def getusers(self, sort=''):
        all_users = self._session.query(_User).all()
        return all_users


    #control can get used based on name (so they can populate a profile)
    def getuser(self, name):
        all_users = self._session.query(_User, _User.name == name)
        for user in all_users:
            if user[1] == True:
                return user[0]

#control can get user based on name (so they can populate a profile)
def getuser(name):
	all_users = session.query(User, User.name == name)
	for user in all_users:
		if user[1] == True:
			return user[0]

#internal use - to print a table
def _printdbrows(rs):
	print "Table %s:" %(rs[0].__tablename__)
	for row in rs:
		print " ", row
